<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="../cwjy/css/app.css" rel="stylesheet">
    <style>
        html::-webkit-scrollbar {
            display: none
        }
    </style>
</head>
<script src="../cwjy/js/app.js"></script>
<script src="../cwjy/js/jquery.min.js"></script>
<body>
<div class="card">
    <div class="card-header">
        <div>
            <div style="float:left;">
                <span style="font-weight: bold;font-size: 20px;text-shadow: 1px 1px 2px #000000;">商品</span>
            </div>
            <div style="float: right;margin-right: 7%">
                <button type="button" class=" " data-feather="plus-circle" data-toggle="modal"
                        data-target="#defaultModalPrimary" onclick="initMode('addData()')"></button>
            </div>
        </div>
        <table class="table table-striped" cellpadding="0" cellspacing="0">
            <thead>
            <tr>
                <th style="width:10%;">序号</th>
                <th style="width:20%;">商品名称</th>
                <th style="width:10%;">商品图片</th>
                <th style="width:10%;">价格</th>
                <th style="width:10%;">库存</th>
                <th style="width:10%;">销量</th>
                <th style="width:10%;">创建时间</th>
                <th style="width:10%;">创建人</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody id="tbodyDiv">

            </tbody>
        </table>
    </div>
</div>

<!--模态框-->
<div class="modal fade" id="defaultModalPrimary" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header" id="modelHead">

            </div>
            <div class="modal-body m-3" style="font-weight: bold;text-shadow: 2px 2px 3px #000000;font-size: 15px" id = "typeStyle">
                <div class="card-body" id="modelDiv" style="margin-top: -6%;font-weight: bold">

                </div>
            </div>
            <div class="modal-footer" id="modelAction">

            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="../cwjy/js/ajaxAll.js"></script>
<script type="text/javascript">

    function removeNodeI(index) {
        $('#P' + index + " i").unbind("click");
        $('#P' + index + " i").click(function () {
            if (confirm('是否删除该节点?')) {
                $(this).parent().remove();
            }
        })
    }




    function typeInit(name, i, id) {
        let temp = "   <div class=\"mb-3 lblx\">\n" +
            "                        <div>\n" +
            "                            <label class=\"form-label\" for=\"image_path\" style=\"font-weight: bold;margin-right: 10px\" id='"+id+"'>" + name + "</label>\n" +
            " <input type=\"text\" size='10' style=\"margin-right: 10px;border: 1px solid #ced4da;border-radius: .2rem;\" id='inputType" + i + "'>    " +
            "<button type=\"button\" data-feather=\"plus-circle\" onclick='add(" + i + ")'></button>\n" +
            "                        </div>\n" +
            "                        <p id=\"P" + i + "\">\n" +
            "                        </p>\n" +
            "                    </div>";
        $('#modelDiv').append(temp);
    }



    function add(index) {
        let inputTypeVal = $('#inputType' + index).val();
        if(inputTypeVal === ""){
            alert("输入为空，请重新输入!")
            return;
        }
        let typeState = inputTypeCheckVal(index, inputTypeVal);
        addTypeDataXX(typeState,index,inputTypeVal)
        $('#inputType' + index).val("");
    }

    function addTypeDataXX(typeState,index,inputTypeVal){
        if (!typeState) {
            let demoDiv = "<button type=\"button\" class=\"btn btn-pill btn-info\"\n" +
                "    style=\"margin-right: 10px;box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);margin-bottom: 5px\">\n" +
                "        <span>" + inputTypeVal + "</span>  <i class=\"fas fa-times\"></i></button>";
            $('#P' + index).append(demoDiv);
            removeNodeI(index);
        }
    }


    function inputTypeCheckVal(type, name) {
        let flag = false;
        $('#P' + type + " span").each(function () {
            let nameSpan = $(this).html();
            if (name === nameSpan) {
                alert('输入类型已存在')
                flag = true;
            }
        })
        return flag;
    }

    function ImageTop() {
        var fils = $("#image_path").get(0).files[0];
        var srcc = window.URL.createObjectURL(fils);
        $('#topImages').attr("src", srcc)
        $('#topImages').css("width", "100px")
        $('#topImages').css("height", "100px")
        $('#topImages').css("margin-top", "10px")
    }


     function addType() {
          addNodeMessage("")
          feather.replace();
          initClassificationDetailedClick();
      }

      function addNodeMessage(name) {
          let temp = "    <div class=\"col-md-12\" >\n" +
              "                                    <div class=\"col-md-11\" style=\"float: left\">\n" +
              "                                        <input type=\"text\" class=\"form-control \"\n" +
              "                                               placeholder=\"类型名称\" value='" + name + "' style=\"margin-bottom: 10px\">\n" +
              "                                    </div>\n" +
              "                                    <div class=\"col-md-1\" style=\"float: left\">\n" +
              "                                   <span>     <button type=\"button\" data-feather=\"x-circle\"\n" +
              "                                                style=\"float: right;margin-top: 15%;color: red\"></button>\n" +
              "                                    </div></span>\n" +
              "                                </div>";
          $('#classification_detailed').append(temp)
      }

      function initClassificationDetailedClick() {
          $('#classification_detailed span').unbind("click")
          $('#classification_detailed span').click(function () {
              if (confirm('是否删除该节点?')) {
                  $(this).parent().parent().remove()
              }
          })
      }

      initClassificationDetailedClick();

      function addData() {
          let product_name = $('#product_name');
          let price = $('#price');
          let sales_price = $('#sales_price');
          let integral = $('#integral');
          let inventory = $('#inventory');
          let category_details = $('#category_details');
          let post_fee = $('#post_fee');
        let classification_detailed_list = [];
         $('#modelDiv .lblx').each(function (i) {
            let commodity_category_id ;
            let type_detailed_array = [];
             $(this).find("label").each(function () {
                 commodity_category_id = $(this)[0].id;
             })
             $(this).find("span").each(function (i) {
                 type_detailed_array[i] = $(this).html();
             })
             let json  = {"commodity_category_id":commodity_category_id,"type_detailed_array":type_detailed_array}
             classification_detailed_list[i] = json;
         })
          let json  = {"product_name":product_name.val(),"price":price.val(),"sales_price":sales_price.val(),"post_fee":post_fee.val(),
              "integral":integral.val(),"inventory":inventory.val(),"category_details":category_details.val(),"classification_detailed_list":classification_detailed_list}
          var myform = new FormData();
          myform.append('file', $("#image_path")[0].files[0]);
          myform.append('record',JSON.stringify(json));
          let url = "http://localhost:8888/cwjy/Commodity/insert";
          let success = "增加成功！";
          let error = "增加失败";
          ajaxUnifiedCallUpdateAndAddFormData(url,myform,success,error)
      }


    let commodityDataCache;
      function getCommodityPage(){
          let url = "http://localhost:8888/cwjy/Commodity/getPage";
          let json = {};
          $.ajax({
              type: 'post',
              async: false,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
              url: url,    //请求发送到Servlet
              contentType: 'application/json;charset=UTF-8',//指定消息请求类型
              data: JSON.stringify(json),
              timeout: 10000,    //超时10s
              success: function (res) { returnLogin(res);
                  commodityDataCache = res.data;
                  forEachCommodity();
              },
              error: function (errorMsg) {
                  //请求失败时执行该函数
                  alert('数据请求失败!');
              }
          });
      }
    getCommodityPage();
    function forEachCommodity(){
        let category_details = "";
        for (let i = 0; i < commodityDataCache.length; i++) {
            let temp = "  <tr>\n" +
                "                <td>"+( i + 1 )+"</td>\n" +
                "                <td>"+commodityDataCache[i].product_name+"</td>\n" +
                "                <td><img src=\"http://localhost:8888/cwjy/images/"+commodityDataCache[i].image_path+"\" width=\"50px\" height=\"50px\"></td>\n" +
                "                <td>"+commodityDataCache[i].price+"</td>\n" +
                "                <td>"+commodityDataCache[i].inventory+"</td>\n" +
                "                <td>"+commodityDataCache[i].sales_volume+"</td>\n" +
                "                <td>"+commodityDataCache[i].create_date+"</td>\n" +
                "                <td class=\"d-none d-md-table-cell\">"+commodityDataCache[i].create_user+"</td>\n" +
                "                <td class=\"table-action\">\n" +
                "                    <a href=\"#\"><i class=\"align-middle\" data-feather=\"eye\" onclick=\"initModeViewDetails('"+commodityDataCache[i].id+"')\"\n" +
                "                                   data-toggle=\"modal\" data-target=\"#defaultModalPrimary\"></i></a>\n" +
                "                    <a href=\"#\"><i class=\"align-middle\" data-feather=\"edit-2\" onclick=\"updateText('"+commodityDataCache[i].id+"')\" data-toggle=\"modal\"\n" +
                "                                   data-target=\"#defaultModalPrimary\"></i></a>\n" +
                "                    <a href=\"#\"><i class=\"align-middle\" data-feather=\"trash\" onclick=\"deleteCommodity('"+commodityDataCache[i].id+"')\"></i></a>\n" +
                "                </td>\n" +
                "            </tr>";
            category_details += temp;
        }
        $('#tbodyDiv').html(category_details)
    }


      function initMode(onType) {
      $('#typeStyle').css("font-weight","bold")
      $('#typeStyle').css("text-shadow","2px 2px 3px #000000")
      $('#typeStyle').css("font-size","15px")
          let category_details = forEachCategory();
          let modiv = " <div class=\"mb-3\">\n" +
              "                        <label class=\"form-label\" for=\"image_path\" style=\"font-weight: bold\">商品图片</label>\n" +
              "                        <input type=\"file\" class=\"form-control \" id=\"image_path\" placeholder=\"商品图片\"\n" +
              "                               onchange=\"ImageTop()\">\n" +
              "                        <img id=\"topImages\">\n" +
              "                    </div>\n" +
              "                    <div class=\"row\">\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"product_name\">商品名称</label>\n" +
              "                            <input type=\"text\" class=\"form-control\" id=\"product_name\" placeholder=\"商品名称\">\n" +
              "                        </div>\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"price\">价格</label>\n" +
              "                            <input type=\"text\" class=\"form-control\" id=\"price\" placeholder=\"价格\">\n" +
              "                        </div>\n" +
              "                    </div>\n" +
              "                    <div class=\"row\">\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"sales_price\">促销价格</label>\n" +
              "                            <input type=\"text\" class=\"form-control\" id=\"sales_price\" placeholder=\"促销价格\">\n" +
              "                        </div>\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"integral\">积分</label>\n" +
              "                            <input type=\"text\" class=\"form-control\" id=\"integral\" placeholder=\"积分\">\n" +
              "                        </div>\n" +
              "                    </div>\n" +
              "                    <div class=\"row\">\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"inventory\">库存</label>\n" +
              "                            <input type=\"text\" class=\"form-control\" id=\"inventory\" placeholder=\"库存\">\n" +
              "                        </div>\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"sales_price\">邮费</label>\n" +
              "                            <input type=\"text\" class=\"form-control\" id=\"post_fee\" placeholder=\"邮费\">\n" +
              "                        </div>\n" +
              "                    </div>" +
              "                    <div class=\"row\">\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"category_details\">类别</label>\n" +
              "                            <select class=\"form-control\" id=\"category_details\" placeholder=\"类别\" oninput='forEachCategoryCommodityCategory()'>\n" +
              "                     "+category_details+"       </select>\n" +
              "                        </div>\n" +
              "                    </div>\n" ;
          $('#modelDiv').html(modiv)

          let modelHead = "  <h3 class=\"modal-title\" id=\"modelHeadText\" style=\"font-weight: bold;text-shadow: 1px 1px 3px #000000;\">\n" +
              "                    商品增加</h3>\n" +
              "                <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">\n" +
              "                    <span aria-hidden=\"true\">×</span>\n" +
              "                </button>";

          $('#modelHead').html(modelHead)

          let modelAction = "  <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">关闭</button>\n" +
              "                <button type=\"button\" class=\"btn btn-primary\" onclick=\""+onType+"\">提交</button>";
          $('#modelAction').html(modelAction)
          forEachCategoryCommodityCategory()
      }


 function deleteCommodity(id){
        if(confirm("是否确认删除！")){
            let url = "http://localhost:8888/cwjy/Commodity/deleteByPrimaryKey";
            let json = {id:id};
            let success = "删除成功";
            let error = "删除失败";
            ajaxUnifiedCallUpdateAndAdd(url,json,success,error)
        }
 }


  let categoryDataCache;
    function getPage() {
        let url = "http://localhost:8888/cwjy/CategoryDetails/getPage";
        let json = {};
        $.ajax({
            type: 'post',
            async: false,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
            url: url,    //请求发送到Servlet
            contentType: 'application/json;charset=UTF-8',//指定消息请求类型
            data: JSON.stringify(json),
            timeout: 10000,    //超时10s
            success: function (res) { returnLogin(res);
                categoryDataCache = res.data;
            },
            error: function (errorMsg) {
                //请求失败时执行该函数
                alert('数据请求失败!');
            }
        });
    }
    getPage();

    function forEachCategory(){
        let category_details = "";
        for (let i = 0; i < categoryDataCache.length; i++) {
            let temp = "<option value=\""+categoryDataCache[i].id+"\">"+categoryDataCache[i].classification_name+"</option>";
            category_details += temp;
        }
        return category_details;
    }

    function forEachCategoryCommodityCategory(){
        $('#modelDiv').find(".lblx").each(function () {
           $(this).remove();
        })
        let id =  $('#category_details').val();
        let data = getDataIdData(categoryDataCache,id).commodity_category;
        for (let i = 0; i < data.length; i++) {
            typeInit(data[i].type_name, i,data[i].id)
        }
        feather.replace();
    }


      function initModeViewDetails(id) {

        let data = getDataIdData(commodityDataCache,id)
          $('#typeStyle').css("font-weight","bold")
          $('#typeStyle').css("text-shadow","2px 2px 3px #000000")
          $('#typeStyle').css("font-size","15px")

          let modelHead = "<h3 class=\"modal-title\">类别详细</h3>\n" +
              "                   <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">\n" +
              "                       <span aria-hidden=\"true\">&times;</span>\n" +
              "                   </button>";


          let modelDiv = " <div class=\"mb-3\">\n" +
              "                        <label class=\"form-label\" for=\"image_path\" style=\"font-weight: bold\">商品图片</label>\n" +
            "\n" +
              "                   <p>     <img id=\"topImages\" src=\"http://localhost:8888/cwjy/images/"+data.image_path+"\" style='width: 150px;height: 150px;'>\n" +
              "              </p>      </div>\n" +
              "                    <div class=\"row\">\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"product_name\">商品名称</label>\n" +
              "                            <input disabled type=\"text\" class=\"form-control\" id=\"product_name\" value='"+data.product_name+"' placeholder=\"商品名称\">\n" +
              "                        </div>\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"price\">价格</label>\n" +
              "                            <input disabled type=\"text\" class=\"form-control\" id=\"price\" value='"+data.price+"' placeholder=\"价格\">\n" +
              "                        </div>\n" +
              "                    </div>\n" +
              "                    <div class=\"row\">\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"sales_price\">促销价格</label>\n" +
              "                            <input disabled type=\"text\" class=\"form-control\" value='"+data.sales_price+"' id=\"sales_price\" placeholder=\"促销价格\">\n" +
              "                        </div>\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"integral\">积分</label>\n" +
              "                            <input disabled type=\"text\" class=\"form-control\" value='"+data.integral+"' id=\"integral\" placeholder=\"积分\">\n" +
              "                        </div>\n" +
              "                    </div>\n" +
              "                    <div class=\"row\">\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"inventory\">库存</label>\n" +
              "                            <input disabled type=\"text\" class=\"form-control\" value='"+data.inventory+"' id=\"inventory\" placeholder=\"库存\">\n" +
              "                        </div>\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"sales_price\">邮费</label>\n" +
              "                            <input disabled type=\"text\" class=\"form-control\" value='"+data.post_fee+"' id=\"post_fee\" placeholder=\"邮费\">\n" +
              "                        </div>\n" +
              "                    </div>" +
              "                    <div class=\"row\">\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"inventory\">销售数量</label>\n" +
              "                            <input disabled type=\"text\" class=\"form-control\" value='"+data.sales_volume+"' id=\"inventory\" placeholder=\"库存\">\n" +
              "                        </div>\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"sales_price\">评价数量</label>\n" +
              "                            <input disabled type=\"text\" class=\"form-control\" value='"+data.evaluation+"' id=\"post_fee\" placeholder=\"邮费\">\n" +
              "                        </div>\n" +
              "                    </div>" +
              "                    <div class=\"row\">\n" +
              "                        <div class=\"mb-3 col-md-6\">\n" +
              "                            <label class=\"form-label\" for=\"category_details\">类别</label>\n" +
              "                            <select  disabled class=\"form-control\"  id=\"category_details\" placeholder=\"类别\" oninput='forEachCategoryCommodityCategory()'>\n" +
              "                 <option value='"+data.category_details+"'>"+data.category_details_name+"</option>     </select>\n" +
              "                        </div>\n" +
              "                    </div>\n" ;
          let modelAction = "  <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">关闭</button>";
          $('#modelHead').html(modelHead)
          $('#modelDiv').html(modelDiv)
          $('#modelAction').html(modelAction)
          forEachCategoryCommodityCategory()
          let commodity_category_list = data.commodity_category_list;
          for (let i = 0; i < commodity_category_list.length; i++) {
              for (let j = 0; j < commodity_category_list[i].classification_detaileds.length; j++) {
                  addTypeDataXX(false,i,commodity_category_list[i].classification_detaileds[j].type_detailed)
              }
          }
          $('#modelDiv input').each(function () {
              $(this).attr("disabled","disabled")
          })
      }

      function updateText(id) {
          let data = getDataIdData(commodityDataCache,id)
          initMode('updateData(\''+id+'\')');
          $('#modelHeadText').html("商品修改")
          /**注入商品名称信息*/
          $('#product_name').val(data.product_name)
          /**注入价格信息*/
          $('#price').val(data.price)
          /**注入销售价格信息*/
          $('#sales_price').val(data.sales_price)
          /**注入积分信息*/
          $('#integral').val(data.integral)
          /**注入库存信息*/
          $('#inventory').val(data.inventory)
          /**注入邮费信息*/
          $('#post_fee').val(data.post_fee)
          /**注入当前数据的类型*/
          $('#category_details option').each(function () {
              if($(this).html() === data.category_details_name){
                  $(this).attr("selected",true)
              }else {
                  $(this).attr("selected",false)
              }
          })
          /**增加类型分类*/
          forEachCategoryCommodityCategory()
          let commodity_category_list = data.commodity_category_list;
          for (let i = 0; i < commodity_category_list.length; i++) {
              for (let j = 0; j < commodity_category_list[i].classification_detaileds.length; j++) {
                  addTypeDataXX(false,i,commodity_category_list[i].classification_detaileds[j].type_detailed)
              }
          }
          /**注入图片路径*/
          $('#topImages').attr("src", "http://localhost:8888/cwjy/images/"+data.image_path)
          $('#topImages').css("width", "100px")
          $('#topImages').css("height", "100px")
          $('#topImages').css("margin-top", "10px")
          /**刷新按钮*/
          initClassificationDetailedClick();
          /**刷新当前页面组件*/
          feather.replace();
      }
      function updateData(id) {
          let product_name = $('#product_name');
          let price = $('#price');
          let sales_price = $('#sales_price');
          let integral = $('#integral');
          let inventory = $('#inventory');
          let category_details = $('#category_details');
          let post_fee = $('#post_fee');
          let classification_detailed_list = [];
          $('#modelDiv .lblx').each(function (i) {
              let commodity_category_id ;
              let type_detailed_array = [];
              $(this).find("label").each(function () {
                  commodity_category_id = $(this)[0].id;
              })
              $(this).find("span").each(function (i) {
                  type_detailed_array[i] = $(this).html();
              })
              let json  = {"commodity_category_id":commodity_category_id,"type_detailed_array":type_detailed_array}
              classification_detailed_list[i] = json;
          })
          let json  = {"id":id,"product_name":product_name.val(),"price":price.val(),"sales_price":sales_price.val(),"post_fee":post_fee.val(),
              "integral":integral.val(),"inventory":inventory.val(),"category_details":category_details.val(),"classification_detailed_list":classification_detailed_list}
          var myform = new FormData();
          let file = $("#image_path")[0].files[0];
          if(file !== undefined){
              myform.append('file', file);
          }else {
              myform.append('file',null);
          }
          myform.append('record',JSON.stringify(json));
          let url = "http://localhost:8888/cwjy/Commodity/updateByPrimaryKeySelective";
          let success = "修改成功！";
          let error = "修改失败";
          ajaxUnifiedCallUpdateAndAddFormData(url,myform,success,error)
      }

</script>

</body>
</html>